//
//  ConfirmPayViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2018/12/5.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit
import SnapKit

class ConfirmPayViewController: UIViewController {

    @IBOutlet weak var payTable: UITableView!
    
    @IBOutlet weak var orderTimeLabel: UILabel!
    
    @IBOutlet weak var preTotalAmountLabel: UILabel!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var preDayAmountLabel: UILabel!
    
    @IBOutlet weak var prePrepareAmountLabel: UILabel!
    
    @IBOutlet weak var preNodeductAmountLabel: UILabel!
    
    @IBOutlet var headerView: UIView!
    
    @IBOutlet weak var payPageInfoLabel: UILabel!
    
    @IBOutlet var paySwith: PaySwith!
    
    var orderId: String?
    
    var timer: Timer?
    
    private var prepayDetail: Order.QueryPrepayDetail? {
        didSet {
            if let data = prepayDetail {
                timer?.invalidate()
                timer = nil
                
                timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                    DispatchQueue.global().async {
                        let now = Date().timeIntervalSince1970
                        var time = Int(now) - data.orderTime
                        time = 15 * 60 - (time < 0 ? 0 : time)
                        let m = time / 60 > 9 ? "\(time / 60)" : "0\(time / 60)"
                        let s = time % 60 > 9 ? "\(time % 60)" : "0\(time % 60)"
                        DispatchQueue.main.async { [weak self] in
                            
                            self?.orderTimeLabel.text = "\(m):\(s)"
                            if time <= 0 {
                                self?.navigationController?.popViewController(animated: true)
                            }
                        }
                    }
                }
                
                preTotalAmountLabel.text = data.preTotalAmount
                timeLabel.text = timeStampToString(timeStamp: data.preStartTime)
                    + " - "
                    + timeStampToString(timeStamp: data.preEndTime)
                preDayAmountLabel.text = data.preDayAmount
                prePrepareAmountLabel.text = data.prePrepareAmount
                preNodeductAmountLabel.text = data.preNodeductAmount
            }
        }
    }
    
    func timeStampToString(timeStamp:Int) -> String {
        let timeSta = TimeInterval(timeStamp)
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = "yyyy/MM/dd HH:mm"
        let date = Date(timeIntervalSince1970: timeSta)
        return dfmatter.string(from: date)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        payPageInfoLabel.text = slipViewController?.config?.dayPayInstruction
        
        if let string = payPageInfoLabel.text {
            let fontSize = payPageInfoLabel.font.pointSize
            let size: CGSize = string.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: fontSize)])
            headerView.height = size.height + 330
        }
        
        guard let orderId = orderId else {
            showError("订单号错误")
            return
        }
        
        paySwith.addObserve { payment, success in
            switch payment {
            case .aliPay:
                if success {
                    self.performSegue(withIdentifier: "preorderSegue", sender: nil)
                } else {
                    XHProgressHUD.showError("你取消了支付")
                }
            case .wePay:
                if success {
                    self.performSegue(withIdentifier: "preorderSegue", sender: nil)
                } else {
                    XHProgressHUD.showError("你已取消支付")
                }
            case .balance, .ticket:
                break
            }
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.queryPrepayDetail(orderId: orderId, success: { [weak self] data in
            JZLoading.hideLoading()
            self?.prepayDetail = data
            
            if let data = data, data.balanceFlag == 0 {

                self?.paySwith.balance = false
                self?.payTable.reloadData()
                
                self?.payTable.snp.makeConstraints { (make) -> Void in
                    make.height.equalTo(100)
                }
            }
        }) { [weak self] msg in
            JZLoading.hideLoading()
            self?.showError(msg)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        timer?.invalidate()
        timer = nil
    }
    
    deinit {
        timer?.invalidate()
        timer = nil
    }
    
    @IBAction func pay(_ sender: UIButton) {
        guard let loc = self.userLocation else {
            showError("未获得经纬度")
            return
        }
        
        guard let sn = prepayDetail?.orderSn else {
            showError("未获得订单详情")
            return
        }
        
        guard let p = paySwith.selected else {
            showError("请选择支付方式")
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.prepayPay(orderSn: sn, payment: p, location: loc, couponSn: paySwith.textField?.text, success: { [weak self] data in
            JZLoading.hideLoading()
            if let payStr = data?.payStr, let self = self {
                switch p {
                case .aliPay:
                    Pay.zhifuPay(payStr: payStr)
                case .wePay:
                    Pay.wechatPay(payStr: payStr)
                case .balance:
                    XHProgressHUD.showSuccess("支付成功")
                    self.performSegue(withIdentifier: "preorderSegue", sender: nil)
                case .ticket:
                    XHProgressHUD.showSuccess("支付成功")
                    self.performSegue(withIdentifier: "preorderSegue", sender: nil)
                }
            }
        }) { [weak self] msg in
            if msg.code == 2011 {
                self?.performSegue(withIdentifier: "preorderSegue", sender: nil)
            } else {
                JZLoading.hideLoading()
                self?.showError(msg)
            }
        }
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "preorderSegue" {
            if let vc = segue.destination as? PreorderViewController {
                vc.orderId = orderId
            }
        } else if segue.identifier == "cancelSegue" {
            if let vc = segue.destination as? DayCancelViewController {
                vc.orderId = orderId
                vc.orderTime = prepayDetail?.orderTime
            }
        }
    }
}
